angular.module('tribalc').controller(
    'registerController',
    ['$scope', 'Api', 'Check', 'Prompt', 'Enum','$state','Alert','$rootScope', function ($scope, Api, Check, Prompt, Enum,$state,Alert,$rootScope) {
        init();
        getCommunities();
        getCitys();
        $scope.selectProvince = selectProvince;
        $scope.upload = {pictures: []};
        $scope.selectTribeAgrState=false;
        // $scope.propertyCompanyN=false;
        $scope.propertyCompanyY=false;
        // $scope.regCompanyInformation.isCompany = false;
        $scope.changeState=changeState;
        function getCommunityIdUrl(){
           return $scope.companyModel.community ?('communities/'+ $scope.companyModel.community.id):false;
        }
        function checkContetWord() {
            var re=/.*[\u4e00-\u9fa5]+.*$/;
            if($scope.regCompanyInformation&&$scope.regCompanyInformation.name && re.test($scope.regCompanyInformation.name)){
                return false
            }else {
                return true
            }
        }

        function checkIsnotLetter(value) {
            var re = /(((400)-(\d{3})-(\d{4}))|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{3,7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/;

            if(!value||re.test(value)){

                return true;

            }else {
                return false;
            }

        }


        function checkFontCount(){
            if ($scope.companyModel.desc && $scope.companyModel.desc.length>100&& $scope.companyModel.desc.length<10){
                return false
            }
            return true
        }

        function changeState() {
            // $scope.selectTribeAgrState= ;
        }
        $scope.judgePropertyCompany = function(type) {
            if(type == 'y'){
                $("#propertyCompanyN")[0].checked = false
            }else{
                $("#propertyCompanyY")[0].checked = false
            }

        };

        function regInformation() {
            var info = {
                name: $scope.regCompanyInformation.name,
                password: $scope.regCompanyInformation.password,
                applyProperty: $scope.propertyCompanyY,
                city: $scope.companyModel.cityObj.name,
                district: $scope.companyModel.districtObj.name,
                province: $scope.companyModel.province.name,
                companyName: $scope.regCompanyInformation.companyName,
                address: $scope.regCompanyInformation.companyAddress,
                companyStaffNum: $scope.regCompanyInformation.companyStaffNum ? $scope.regCompanyInformation.companyNature : null,
                companyIndustry: $scope.regCompanyInformation.companyIndustry ? $scope.regCompanyInformation.companyIndustry : null,
                companyNature: $scope.regCompanyInformation.companyNature ? $scope.regCompanyInformation.companyNature : null,
                linkman: $scope.regCompanyInformation.contactsName,
                department: $scope.regCompanyInformation.department,
                phone: $scope.regCompanyInformation.phone,
                mobilePhone: $scope.regCompanyInformation.mobilePhone,
                verificationCode: $scope.regCompanyInformation.vcode,
                email: $scope.regCompanyInformation.email,
                logo: $scope.logo,
                desc:$scope.companyModel.desc,
                pictures: $scope.upload.pictures
            };
            if ($scope.companyModel && $scope.companyModel.community) {
                info.communityId = $scope.companyModel.community.id;
                info.communityName = $scope.companyModel.community ? $scope.companyModel.community.name : ''
            }
            return info

        }

        $scope.companyOptions = {
            num: Enum.companyNumberOptions,
            industry: Enum.companyIndustryOptions,
            nature: Enum.companyNatureOptions
        };


        function init() {
            // $scope.companyModel = {
            //     province: '北京'
            //
            //
            // }
            $scope.uploadCompanyPictures = uploadCompanyPictures;
            $scope.uploadCompanyLogo = uploadCompanyLogo;

        }

        $scope.showWarn = function (key) {
            var $elementErr = $('#remind_err_' + key);
            if ($elementErr[0].className.indexOf('hide') > -1) {
                $('#remind_' + key).removeClass('hide')
            }

        };
        function checkKeyMustInput(key) {
            var KeyMustInput=['username','password','companyName','companyAddress','contactsName','mobilePhone']
            if(KeyMustInput.indexOf(key)>-1){
                return true;
            }else {
                return false;
            }
        }
        $scope.checkInputValue = function (value, key) {
            var $element = $('#remind_' + key);
            var $elementErr = $('#remind_err_' + key);
            if (Check[key](value)||(!checkKeyMustInput(key)&&!value)) {
                $elementErr.addClass('hide');
                $element.addClass('hide');
                return
            }
            $element.addClass('hide');
            $elementErr.removeClass('hide')
        };
        $scope.checkPassword = function (password, repassword, key) {
            var $element = $('#remind_' + key);
            var $elementErr = $('#remind_err_' + key);
            if (Check[key](password, repassword)) {
                $elementErr.addClass('hide')
                $element.addClass('hide')
                return
            }
            $element.addClass('hide')
            $elementErr.removeClass('hide')
        };
        $scope.sendSms = function (phone) {
            if (!phone) {
                return Alert.alertBox('请输入手机号')
            }
            if (!Check.mobilePhone(phone)) {
                return Alert.alertBox('请检查手机号')
            }

            Api.sendPhoneVerifyCode(phone, function (result) {

            })

        };
        function judgePropertyCompany(id) {
             var state=$('#id').attr('ng-checked');

        }

        function checkIsEmpty() {
            return $scope.companyModel && $scope.companyModel.cityObj && $scope.companyModel.districtObj && $scope.companyModel.province &&
                $scope.regCompanyInformation && $scope.companyModel.community

        }


        $scope.register = function (phone) {
            $scope.selectTribeAgrState  = $('#terms')[0].checked;

            if(!checkContetWord()){
                return Alert.alertBox('用户名不可含汉字')
            }

            if (!checkIsnotLetter(phone)){
                return Alert.alertBox('请检查固定电话输入格式')
            }
            if (!checkIsEmpty()) {

                return Alert.alertBox('请检查信息输入是否完整')
            }
            if(!$scope.selectTribeAgrState){
                return Alert.alertBox(('请阅读部落协议'))
            }

            if(!Check.desc($scope.companyModel.desc)){
                return Alert.alertBox('请检查公司描述')
            }
            if (!checkRePassword($scope.regCompanyInformation.password, $scope.regCompanyInformation.repassword)) {
                return Alert.alertBox('输入密码不一致')

            }
            var companyInfo = regInformation();
            formatPicturePath(companyInfo);
            if (checkCompanyInfo(companyInfo)) {
                // console.log(companyInfo);
                return Api.register(companyInfo, function () {
                    Alert.alertBox('注册成功',null)
                    $state.go('login');
                }, function () {
                    Alert.alertBox("注册失败")
                }, true)
            }
            Alert.alertBox('请检查输入信息')

        }

        function formatPicturePath(companyDetail) {
            var aliyu="https://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/";
            if (companyDetail.logo && companyDetail.logo.indexOf(aliyu) !== -1) {
                companyDetail.logo = "oss://" + companyDetail.logo.split(aliyu)[1];
            }
            if (companyDetail.licensePicture && companyDetail.licensePicture.indexOf(aliyu) !== -1) {
                companyDetail.licensePicture = "oss://" + companyDetail.licensePicture.split(aliyu)[1];
            }
            if (companyDetail.underCover && companyDetail.underCover.indexOf(aliyu) !== -1) {
                companyDetail.underCover = "oss://" + companyDetail.underCover.split(aliyu)[1];
            }
            if (companyDetail.pictures){
                var pictures=[];
                for (var i=0;i<companyDetail.pictures.length;i++){
                    if(companyDetail.pictures[i].indexOf(aliyu) !== -1){
                        companyDetail.pictures[i]="oss://" + companyDetail.pictures[i].split(aliyu)[1];
                    }

                    pictures.push(companyDetail.pictures[i])
                }
                return companyDetail.pictures=pictures
            }
            return companyDetail;
        }

        function getCommunities() {
            Api.getCommunityList(function (result) {
                $scope.cummunityList = result.data;
            })
        }

        $scope.companyModel = {};
        function getCitys() {
            Api.getChinaCitysJson(function (result) {
                $scope.citys = result;
            });
        }

        function checkCompanyInfo(companyInfo) {
            var needCheck = ['name', 'password', 'companyName', 'address', 'linkman', 'mobilePhone'];
            var test = {
                name: 'username',
                password: 'password',
                companyName: 'companyName',
                address: 'companyAddress',
                linkman: 'contactsName',
                mobilePhone: 'mobilePhone'
            };
            var status = true;
            for (var i = 0; i < needCheck.length; i++) {
                if (!Check[test[needCheck[i]]](companyInfo[needCheck[i]])) {
                    status = false;
                    break;
                }
            }
            return status
        }

        function selectProvince(province) {
            $scope.companyModel.provinceObj = province
        }

        $scope.selectCity = function (city) {
            $scope.companyModel.cityObj = city
        };
        $scope.to_left_image_container = function () {
            $('#imageContainer').removeClass('pro-write-picture-right')
        }
        $scope.to_right_image_container = function () {
            $('#imageContainer').addClass('pro-write-picture-right')
        }

        function uploadCompanyLogo(ele) {
            var $divEle = $(ele).parent();
            var file = ele.files[0];
            var index = $(".pro-write-picture-content .pro-write-pictures").index($($divEle).parent());
            var communityIdUrl = getCommunityIdUrl();
            if(!communityIdUrl){
                return $scope.$apply(Alert.alertBox('请选择社区'))
            }
            setupPicture($($divEle), file);
            // uploadNumber++;

            uploadPicture(file,communityIdUrl, function (imgUrl) {
                $scope.$apply(function () {
                    $scope.logo = imgUrl;
                });
            });
        }

        function uploadCompanyPictures(ele) {
            var $divEle = $(ele).parent();
            var file = ele.files[0];
            var index = $(".pro-write-picture-content .pro-write-pictures").index($($divEle).parent());
             var communityIdUrl = getCommunityIdUrl();
            if(!communityIdUrl){

                return $scope.$apply(Alert.alertBox('请选择社区'))
            }
            setupPictures($($divEle), file);
            // uploadNumber++;
            uploadPicture(file, communityIdUrl,function (imgUrl) {
                $scope.$apply(function () {
                    $scope.upload.pictures[index] = imgUrl;
                });
            });
        }


        function uploadPicture(file, communityIdUrl,sucFuc) {

            Api.uploadLogoPicture(hex_md5(file),communityIdUrl, function (result) { //api 修改
                Api.callAliyunPicture(result.data.objectKey, result.data.url, file, function (result) {
                    sucFuc(result);
                }, function () {

                })
            }, function () {

            });
        }

        function setupPictures($divEle, file) {
            var fileReader = new FileReader();
            fileReader.onload = function () {
                var imgSrc = fileReader.result;
                if (imgSrc) {
                    $divEle.find('img').attr("src", imgSrc);
                    $divEle.addClass("pro-logo-completed");

                }
            };
            fileReader.readAsDataURL(file);
        }

        function setupPicture($divEle, file) {
            var fileReader = new FileReader();
            fileReader.onload = function () {
                var imgSrc = fileReader.result;
                if (imgSrc) {
                    $divEle.find('img').attr("src", imgSrc);
                    $divEle.addClass("pro-logo-completed");
                }
            };
            fileReader.readAsDataURL(file);
        }







        function checkRePassword(password, repassword) {
            return password == repassword;
        }

    }]
);
